<template>
  <el-dialog v-if="load" :title="form.dc_id ? '编辑' : '添加'" v-model="visible" append-to-body :close-on-click-modal="false" :z-index="2000" width="500px" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <el-form-item label="部门" prop="department_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <VCascader v-model="form.department_id" type="1" placeholder="请选择" class="w-full" checkStrictly />
      </el-form-item>
      <el-form-item label="下单时效" prop="order_day" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <el-input-number v-model="form.order_day" :controls="false" :min="0" :step="1" :precision="0" placeholder="请输入" class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const formRef = ref()

// 打开弹窗
const open = async (dc_id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {}
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  if(dc_id) {
    api.detail({dc_id}).then(res => {
      form.value = res.data
    })
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = async() => {
  if (!await formRef?.value.validate()) return
  loadings.submit = true
  api[form.value.dc_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>